package com.shuang.tree8;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Stack;

public class PostorderTraversal {

    //方法三：统一格式迭代法
    public List<Integer> postorderTraversal(TreeNode root) {
        //后序遍历
        List<Integer> result = new ArrayList<Integer>();

        if (root == null) {
            return result;
        }

        //后序遍历 左右中 入栈顺序 中右左
        //定义栈
        Stack<TreeNode> stack = new Stack<>();
        stack.push(root);

        while (!stack.isEmpty()) {

            TreeNode node = stack.peek();

            if (node != null) {
                //弹出中
                stack.pop();

                //中入栈
                stack.push(node);

                //标记
                stack.push(null);

                //右入栈
                if (node.right != null) {
                    stack.push(node.right);
                }

                //左入栈
                if (node.left != null) {
                    stack.push(node.left);
                }
            } else {
                stack.pop(); //弹出空

                node = stack.pop();

                result.add(node.val);
            }

        }

        return result;
    }
}
